package com.sinosoft.handler;

import com.sinosoft.domain.ApiException;
import com.sinosoft.domain.CodeEnums;
import com.sinosoft.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author hyy85
 * @version 1.0
 * @date: 13/6/2018 下午 12:14<br/>
 * @description 全局异常捕获
 * @since 1.8
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result jsonErrorHandler(Exception e) {
        Result baseRes = new Result();
        //自定义业务异常
        if (e instanceof ApiException) {
            ApiException ae = (ApiException) e;
            baseRes.setReturnCode(ae.getCode());
            baseRes.setReturnMsg(ae.getErrMsg());
            return baseRes;
        }
        //未知异常 空指针什么的
        logger.error(e.getLocalizedMessage());
        baseRes.setReturnCode(CodeEnums.SYSTEM_ERR.getCode());
        baseRes.setReturnMsg(CodeEnums.SYSTEM_ERR.getMsg());
        return baseRes;
    }

}
